<template>
  <div class="stakeholder-container">
    <el-card class="stakeholder-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><UserFilled /></el-icon>
            干系人管理
            <el-tag v-if="props.projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
              {{ props.projectData.project_name }}
            </el-tag>
          </h2>
          <p class="description">
            管理项目干系人及其职责分配
            <span v-if="props.projectData.project_id" style="color: #e6a23c; font-weight: 500;">
              (项目编号: {{ props.projectData.project_id }})
            </span>
          </p>
        </div>
        <el-button v-if="hasPermission" type="primary" @click="openDialog()" class="create-btn">
          <el-icon><Plus /></el-icon>
          添加干系人
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索干系人姓名、公司、职务..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterCompany" placeholder="公司筛选" clearable>
          <el-option
            v-for="company in companyOptions"
            :key="company"
            :label="company"
            :value="company"
          />
        </el-select>
      </div>

      <!-- 干系人表格 -->
      <el-table
        :data="filteredStakeholderList"
        stripe
        border
        class="stakeholder-table"
        v-loading="loading"
        empty-text="暂无干系人数据"
      >
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="company" label="公司" min-width="150" />
        <el-table-column prop="position" label="职务" min-width="120" />
        <el-table-column prop="phone" label="联系电话" min-width="150" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="office_location" label="办公地点" min-width="150" />
        <el-table-column prop="note" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" v-if="hasPermission">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 干系人创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑干系人' : '添加干系人'"
      width="600px"
      align-center
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="project_id">
              <el-input v-model="form.project_id" placeholder="项目编号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司" prop="company">
              <el-input v-model="form.company" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="position">
              <el-select v-model="form.position" placeholder="请选择职务" style="width: 100%">
                <el-option label="项目经理" value="项目经理" />
                <el-option label="甲方代表" value="甲方代表" />
                <el-option label="技术负责人" value="技术负责人" />
                <el-option label="软件研发" value="软件研发" />
                <el-option label="销售代表" value="销售代表" />
                <el-option label="分包代表" value="分包代表" />
                <el-option label="供应商代表" value="供应商代表" />
                <el-option label="监理" value="监理" />
                <el-option label="项目发起人" value="项目发起人" />
                <el-option label="业务负责人" value="业务负责人" />
                <el-option label="质量负责人" value="质量负责人" />
                <el-option label="安全负责人" value="安全负责人" />
                <el-option label="财务负责人" value="财务负责人" />
                <el-option label="采购负责人" value="采购负责人" />
                <el-option label="人力资源负责人" value="人力资源负责人" />
                <el-option label="法务负责人" value="法务负责人" />
                <el-option label="运维负责人" value="运维负责人" />
                <el-option label="测试负责人" value="测试负责人" />
                <el-option label="UI/UX设计师" value="UI/UX设计师" />
                <el-option label="产品经理" value="产品经理" />
                <el-option label="架构师" value="架构师" />
                <el-option label="开发工程师" value="开发工程师" />
                <el-option label="测试工程师" value="测试工程师" />
                <el-option label="运维工程师" value="运维工程师" />
                <el-option label="数据分析师" value="数据分析师" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码，如：13800138000" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱地址，如：example@company.com" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="办公地点" prop="office_location">
          <el-input v-model="form.office_location" placeholder="请输入办公地点" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import { getStakeholderList, createStakeholder, updateStakeholder, deleteStakeholder } from '../../api/stakeholder'

// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

const stakeholderList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const searchKeyword = ref('')
const filterCompany = ref('')
const formRef = ref()
const submitLoading = ref(false)

const form = ref({
  id: null,
  project_id: '',
  name: '',
  company: '',
  position: '',
  phone: '',
  email: '',
  office_location: '',
  note: ''
})

const formRules = {
  project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
}

// 过滤后的干系人列表
const filteredStakeholderList = computed(() => {
  const currentProjectId = props.projectData.project_id || props.projectId
  
  // 首先按项目ID过滤
  let filtered = stakeholderList.value.filter(stakeholder => 
    stakeholder.project_id === currentProjectId
  )
  
  // 然后按搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(stakeholder => 
      stakeholder.name.toLowerCase().includes(keyword) ||
      stakeholder.company?.toLowerCase().includes(keyword) ||
      stakeholder.position?.toLowerCase().includes(keyword)
    )
  }
  
  // 最后按公司过滤
  if (filterCompany.value) {
    filtered = filtered.filter(stakeholder => stakeholder.company === filterCompany.value)
  }
  
  return filtered
})

// 公司选项
const companyOptions = computed(() => {
  const companies = [...new Set(stakeholderList.value.map(item => item.company).filter(Boolean))]
  return companies
})

// 打开对话框
function openDialog(stakeholder = null) {
  if (stakeholder) {
    form.value = { ...stakeholder }
  } else {
    form.value = {
      id: null,
      project_id: props.projectData.project_id || props.projectId || '',
      name: '',
      company: '',
      position: '',
      phone: '',
      email: '',
      office_location: '',
      note: ''
    }
  }
  dialogVisible.value = true
}

// 生成32位GUID
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  }).replace(/-/g, '')
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      if (!form.value.id) {
        // 创建干系人时自动生成GUID
        const payload = { ...form.value }
        payload.id = generateGUID()
        console.log('创建干系人，payload:', payload)
        await createStakeholder(payload)
        ElMessage.success('干系人添加成功')
      } else {
        // 更新干系人
        console.log('更新干系人，payload:', form.value)
        await updateStakeholder(form.value.id, form.value)
        ElMessage.success('干系人更新成功')
      }
      
      dialogVisible.value = false
      loadStakeholders()
    } catch (error) {
      ElMessage.error('操作失败，请重试')
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 删除干系人
function handleDelete(id) {
  ElMessageBox.confirm('确认删除该干系人？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteStakeholder(id)
      ElMessage.success('删除成功')
      loadStakeholders()
    } catch (error) {
      ElMessage.error('删除失败，请重试')
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 加载干系人列表
async function loadStakeholders() {
  loading.value = true
  try {
    const params = {}
    const currentProjectId = props.projectData.project_id || props.projectId
    
    // 必须有项目编号才加载干系人
    if (currentProjectId) {
      params.filter = `project_id:eq:${currentProjectId}`
      console.log('加载项目干系人，项目ID:', currentProjectId)
      
      const res = await getStakeholderList(params)
      // 确保数据是数组格式，即使没有数据也要设置为空数组
      stakeholderList.value = Array.isArray(res.records) ? res.records : []
    } else {
      // 没有项目编号时，不显示任何干系人
      stakeholderList.value = []
      console.log('没有项目编号，不加载干系人')
    }
  } catch (error) {
    ElMessage.error('加载干系人列表失败')
    console.error('加载干系人列表失败:', error)
    // 出错时也要设置为空数组
    stakeholderList.value = []
  } finally {
    loading.value = false
  }
}

// 监听项目数据变化
watch(() => props.projectData, (newProjectData) => {
  if (newProjectData && newProjectData.project_id) {
    // 如果当前正在编辑且项目编号为空，则自动填充
    if (dialogVisible.value && !form.value.project_id) {
      form.value.project_id = newProjectData.project_id
    }
    // 重新加载干系人列表
    loadStakeholders()
  }
}, { deep: true })

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    console.log('项目ID变化，重新加载干系人:', newProjectId)
    loadStakeholders()
  }
})

onMounted(() => {
  loadStakeholders()
})
</script>

<style scoped>
.stakeholder-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.stakeholder-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #409eff;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.stakeholder-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}
</style> 